Monday, May 12, 2025
News PouroverAI
Visit PourOver.AI
No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
News PouroverAI
No Result
View All Result

Interpreting Random Forests. Comprehensive guide on Random Forest… | by Mariya Mansurova | Oct, 2023

October 8, 2023
in AI Technology
Reading Time: 4 mins read
0 0
A A
0
Share on FacebookShare on Twitter


There is a lot of hype about Large Language Models nowadays, but it doesn’t mean that old-school ML approaches now deserve extinction. I doubt that ChatGPT will be helpful if you give it a dataset with hundreds numeric features and ask it to predict a target value.

Neural Networks are usually the best solution in case of unstructured data (for example, texts, images or audio). But, for tabular data, we can still benefit from the good old Random Forest.

The most significant advantages of Random Forest algorithms are the following:

  • You only need to do a little data preprocessing.
  • It’s rather difficult to screw up with Random Forests. You won’t face overfitting issues if you have enough trees in your ensemble since adding more trees decreases the error.
  • It’s easy to interpret results.

That’s why Random Forest could be a good candidate for your first model when starting a new task with tabular data.

In this article, I would like to cover the basics of Random Forests and go through approaches to interpreting model results.

We will learn how to find answers to the following questions:

  • What features are important, and which ones are redundant and can be removed?
  • How does each feature value affect our target metric?
  • What are the factors for each prediction?
  • How to estimate the confidence of each prediction?

We will be using the Wine Quality dataset. It shows the relation between wine quality and physicochemical test for the different Portuguese “Vinho Verde” wine variants. We will try to predict wine quality based on wine characteristics.

With decision trees, we don’t need to do a lot of preprocessing:

  • We don’t need to create dummy variables since the algorithm can handle it automatically.
  • We don’t need to do normalisation or get rid of outliers because only ordering matters. So, Decision Tree based models are resistant to outliers.

However, the scikit-learn realisation of Decision Trees can’t work with categorical variables or Null values. So, we have to handle it ourselves.

Fortunately, there are no missing values in our dataset. df.isna().sum().sum() 0

And we only need to transform the type variable (‘red’ or ‘white’) from string to integer. We can use pandas Categorical transformation for it.

categories = {}
cat_columns = ['type']
for p in cat_columns:
    df[p] = pd.Categorical(df[p])
    categories[p] = df[p].cat.categories
df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)
print(categories)  {'type': Index(['red', 'white'], dtype='object')}

Now, df['type'] equals 0 for red wines and 1 for white vines.

The other crucial part of preprocessing is to split our dataset into train and validation sets. So, we can use a validation set to assess our model’s quality.

import sklearn.model_selection
train_df, val_df = sklearn.model_selection.train_test_split(df, test_size=0.2)
train_X, train_y = train_df.drop(['quality'], axis = 1), train_df.quality
val_X, val_y = val_df.drop(['quality'], axis = 1), val_df.quality
print(train_X.shape, val_X.shape) (5197, 12) (1300, 12)

We’ve finished the preprocessing step and are ready to move on to the most exciting part — training models.

Before jumping into the training, let’s spend some time understanding how Random Forests work.

Random Forest is an ensemble of Decision Trees. So, we should start with the elementary building block — Decision Tree.

In our example of predicting wine quality, we will be solving a regression task, so let’s start with it.

Decision Tree: Regression

Let’s fit a default decision tree model.

import sklearn.tree
import graphviz
model = sklearn.tree.DecisionTreeRegressor(max_depth=3)
# I've limited max_depth mostly for visualisation purposes
model.fit(train_X, train_y)

One of the most significant advantages of Decision Trees is that we can easily interpret these models — it’s just a set of questions. Let’s visualise it.

dot_data = sklearn.tree.export_graphviz(model, out_file=None,feature_names = train_X.columns,filled = True)
graph = graphviz.Source(dot_data)
# saving tree to png file
png_bytes = graph.pipe(format='png')
with open('decision_tree.png','wb') as f:
    f.write(png_bytes)

Graph by author

As you can see, the Decision Tree consists of binary splits. On each node, we are splitting our dataset into 2.

Finally, we calculate predictions for the leaf nodes as an average of all data points in this node.

Side note: Because Decision Tree returns an average of all data points for a leaf node, Decision Trees are pretty bad in extrapolation. So, you need to keep an eye on the feature distributions during training and inference.

Let’s brainstorm how to identify the best split for our dataset. We can start with one variable and define the optimal division for it.

Suppose we have a feature with four unique values: 1, 2, 3 and 4. Then, there are three possible thresholds between them.

Graph by author

We can consequently take each threshold and calculate predicted values for our data as an average value for leaf nodes. Then, we can use these predicted values to get MSE (Mean Square Error) for each threshold. The best split will be the one with the lowest MSE. By default, DecisionTreeRegressor from scikit-learn works similarly and uses MSE as a criterion.

Let’s calculate the best split for sulphates feature manually to understand better how it works.

def get_binary_split_for_param(param, X, y):
    uniq_vals = list(sorted(X[param].unique()))
    tmp_data = []
    for i in range(1, len(uniq_vals)):
        threshold = 0.5 * (uniq_vals[i-1] + uniq_vals[i])
        # split dataset by threshold
        split_left = y[X[param] <= threshold]
        split_right = y[X[param] > threshold]
        # calculate predicted values for each split
        pred_left = split_left.mean()
        pred_right = split_right.mean()
        num_left = split_left.shape[0]
        num_right = split_right.shape[0]
        mse_left = ((split_left - pred_left) * (split_left - pred_left)).mean()
        mse_right = ((split_right - pred_right) * (split_right - pred_right)).mean()
        mse = mse_left * num_left / (num_left + num_right) \\
            + mse_right * num_right / (num_left + num_right)
        tmp_data.append({'param': param,
                         'threshold': threshold,
                         'mse': mse})
    return pd.DataFrame(tmp_data).sort_values('mse')
get_binary_split_for_param('sulphates', train_X, train_y).head(5)
|   param |  threshold |       mse |
|---------|------------|-----------|
| sulphates |      0.685 | 0.758495 |
| sulphates |      0.675 | 0.758794 |
| sulphates |      0.705 | 0.759065 |
| sulphates |      0.715 | 0.759071 |
| sulphates |      0.635 | 0.759495 |

We can see that for sulphates, the best threshold is 0.685 since it gives



Source link

Tags: comprehensiveForestâForestsGuideInterpretingMansurovaMariyaOctRandom
Previous Post

10 COOLEST AI Inventions You Can BUY Right Now

Next Post

Top Digital Marketing Trends you Should Consider in 2023

Related Posts

How insurance companies can use synthetic data to fight bias
AI Technology

How insurance companies can use synthetic data to fight bias

June 10, 2024
From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset
AI Technology

From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

June 10, 2024
Decoding Decoder-Only Transformers: Insights from Google DeepMind’s Paper
AI Technology

Decoding Decoder-Only Transformers: Insights from Google DeepMind’s Paper

June 9, 2024
How Game Theory Can Make AI More Reliable
AI Technology

How Game Theory Can Make AI More Reliable

June 9, 2024
Buffer of Thoughts (BoT): A Novel Thought-Augmented Reasoning AI Approach for Enhancing Accuracy, Efficiency, and Robustness of LLMs
AI Technology

Buffer of Thoughts (BoT): A Novel Thought-Augmented Reasoning AI Approach for Enhancing Accuracy, Efficiency, and Robustness of LLMs

June 9, 2024
Deciphering Doubt: Navigating Uncertainty in LLM Responses
AI Technology

Deciphering Doubt: Navigating Uncertainty in LLM Responses

June 9, 2024
Next Post
Top Digital Marketing Trends you Should Consider in 2023

Top Digital Marketing Trends you Should Consider in 2023

What is the cloud? | CNBC Explains

What is the cloud? | CNBC Explains

Shawbrook makes offer for Co-op Bank, eyes fresh Metro Bank bid –sources By Reuters

Shawbrook makes offer for Co-op Bank, eyes fresh Metro Bank bid –sources By Reuters

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Trending
  • Comments
  • Latest
Is C.AI Down? Here Is What To Do Now

Is C.AI Down? Here Is What To Do Now

January 10, 2024
Porfo: Revolutionizing the Crypto Wallet Landscape

Porfo: Revolutionizing the Crypto Wallet Landscape

October 9, 2023
23 Plagiarism Facts and Statistics to Analyze Latest Trends

23 Plagiarism Facts and Statistics to Analyze Latest Trends

June 4, 2024
A Complete Guide to BERT with Code | by Bradney Smith | May, 2024

A Complete Guide to BERT with Code | by Bradney Smith | May, 2024

May 19, 2024
How To Build A Quiz App With JavaScript for Beginners

How To Build A Quiz App With JavaScript for Beginners

February 22, 2024
Saginaw HMI Enclosures and Suspension Arm Systems from AutomationDirect – Library.Automationdirect.com

Saginaw HMI Enclosures and Suspension Arm Systems from AutomationDirect – Library.Automationdirect.com

December 6, 2023
Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

June 10, 2024
AI Compared: Which Assistant Is the Best?

AI Compared: Which Assistant Is the Best?

June 10, 2024
How insurance companies can use synthetic data to fight bias

How insurance companies can use synthetic data to fight bias

June 10, 2024
5 SLA metrics you should be monitoring

5 SLA metrics you should be monitoring

June 10, 2024
From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

June 10, 2024
UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

June 10, 2024
Facebook Twitter LinkedIn Pinterest RSS
News PouroverAI

The latest news and updates about the AI Technology and Latest Tech Updates around the world... PouroverAI keeps you in the loop.

CATEGORIES

  • AI Technology
  • Automation
  • Blockchain
  • Business
  • Cloud & Programming
  • Data Science & ML
  • Digital Marketing
  • Front-Tech
  • Uncategorized

SITEMAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2023 PouroverAI News.
PouroverAI News

No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing

Copyright © 2023 PouroverAI News.
PouroverAI News

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms bellow to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In